package com.linln.admin.message.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.linln.admin.message.validator.MessageTypeValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.message.domain.MessageType;
import com.linln.modules.message.service.MessageTypeService;
import com.linln.modules.system.domain.Dept;

/**
 * @author hct
 * @date 2019/09/12
 */
@Controller
@RequestMapping("/message/type")
public class MessageTypeController {

    @Autowired
    private MessageTypeService typeService;
 
    /**
     * 跳转到列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("message:type:index")
    public String index(Model model) {
        String search = HttpServletUtil.getRequest().getQueryString();
        model.addAttribute("search", search);
        return "/message/type/index";
    }

    /**
     * 部门数据列表
     */
    @GetMapping("/list")
    @RequiresPermissions(value = {"message:type:index", "message:type:index"}, logical = Logical.OR)
    @ResponseBody
    public ResultVo list(MessageType type) {
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching().
                withMatcher("title", match -> match.contains());
        // 获取部门列表
        Example<MessageType> example = Example.of(type, matcher);
        Sort sort = new Sort(Sort.Direction.ASC, "num");
        List<MessageType> list = typeService.getListByExample(example, sort);
        return ResultVoUtil.success(list);
    }
    
    
    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("message:type:add")
    public String toAdd() {
        return "/message/type/add";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/addSon/{pid}")
    @RequiresPermissions("message:type:addSon")
    public String toAddSon(Model model,MessageType type,@PathVariable Long pid) {
    	 ExampleMatcher matcher = ExampleMatcher.matching().
                 withMatcher("title", match -> match.contains());
    	  Example<MessageType> example = Example.of(type, matcher);
    	  type.setPid(0L);
          Sort sort = new Sort(Sort.Direction.ASC, "num");
          List<MessageType> list = typeService.getListByExample(example, sort);
          model.addAttribute("list", list);
          model.addAttribute("pid", pid);

        return "/message/type/addSon";
    }
    
    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("message:type:edit")
    public String toEdit(@PathVariable("id") MessageType type, Model model) {
        model.addAttribute("type", type);
        if(type.getPid()==0){
        return "/message/type/add";
        }else{
        	ExampleMatcher matcher = ExampleMatcher.matching().
                    withMatcher("title", match -> match.contains());
        	MessageType typenew=new MessageType();
        	typenew.setPid(0L);
            Example<MessageType> example = Example.of(typenew, matcher);
             Sort sort = new Sort(Sort.Direction.ASC, "num");
        List<MessageType> list = typeService.getListByExample(example, sort);
        model.addAttribute("list", list);
        return "/message/type/addSon";
       }
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"message:type:add", "message:type:edit"})
    @ResponseBody
    public ResultVo save(@Validated MessageTypeValid valid, MessageType type) {
    	
    	 if (type.getId() == null) {
             // 排序为空时，添加到最后
             if(type.getNum() == null){
                 Integer sortMax = typeService.getSortMax(type.getPid());
                 type.setNum(sortMax !=null ? sortMax - 1 : 0);
             }
         }

         // 添加/更新全部上级序号
         if (type.getPid() != 0) {
        	 MessageType pDept = typeService.getById(type.getPid());
             type.setPids(pDept.getPids() + ",[" + type.getPid() + "]");
         } else {
        	 type.setPids("[0]");
         }

         // 将验证的数据复制给实体类
         if (type.getId() != null) {
        	 MessageType beDept = typeService.getById(type.getId());
             EntityBeanUtil.copyProperties(beDept, type, "type");
         }

         /*// 排序功能
         Integer sort = type.getNum();
         Long notId = type.getId() != null ? type.getId() : 0;
         List<MessageType> levelDept = typeService.getListByPid(type.getPid(), notId);
         levelDept.add(sort, type);
         for (int i = 1; i <= levelDept.size(); i++) {
             levelDept.get(i - 1).setNum(i);
         }*/
        // 保存数据
        typeService.save(type);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("message:type:detail")
    public String toDetail(@PathVariable("id") MessageType type, Model model) {
        model.addAttribute("type",type);
        return "/message/type/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("message:type:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (typeService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}